<?php
/**
 * @Name  : NodeLogic.php
 * @Author: yashuai<1762910894@qq.com>
 */

namespace App\Http\Logic\Rbac;

use App\Http\Logic\BaseLogic;
use App\Http\Model\Rbac\NodeModel;
use App\Http\Model\Rbac\UserModel;
use HugCode\PhpUnits\Utils\UtilArray;
use HugCode\PhpUnits\Frame\Code\ConstCode;

class NodeLogic extends BaseLogic
{

    /**
     * @Desc 添加
     * @return bool|int
     * @throws \App\Exceptions\ThrowException
     * @author yashuai<1762910894@qq.com>
     */
    public function create()
    {
        return NodeModel::newInsert($this->getParamsTableData());
    }

    /**
     * @Desc 更新
     * @return int
     * @throws \App\Exceptions\ThrowException
     * @author yashuai<1762910894@qq.com>
     */
    public function update()
    {
        $nodeID = $this->params['NodeID'];
        NodeModel::recordExist($nodeID, 'NodeID', 'NodeStatus');

        return NodeModel::query()->where(['NodeID' => $nodeID])->update($this->getParamsTableData());
    }


    /**
     * @Desc 修改状态
     * @return int
     * @author yashuai<1762910894@qq.com>
     */
    public function status()
    {
        return NodeModel::query()->where(['NodeID' => $this->params['ID']])->update([
            'NodeStatus' => $this->params['Status'],
        ]);
    }

    /**
     * @Desc   获取用户所有菜单节点树
     * @param boolean $selectButton 是否查询按钮
     * @return array
     * @throws \App\Exceptions\ThrowException
     * @author yashuai<1762910894@qq.com>
     */
    public function getUserNode($selectButton = false)
    {
        $info   = UserModel::userExist($this->params['UserID'], true);
        $select = [
            'NodeID as menuId',
            'NodeName as title',
            'ParentID as parentId',
            'ControllerName',
            'ActionName',
            'NodeIcon as icon',
            'NodeShowType'
        ];
        $where  = [
            ['NodeStatus', '=', ConstCode::BASIC_STATUS_NORMAL],
        ];
        if ($selectButton === false) {
            $where[] = ['NodeType', '=', ConstCode::NODE_TYPE_MENU];
        }
        $query = NodeModel::query()->where($where)->select($select)->orderBy('NodeOrder', 'ASC');
        if ($info['IsSuper'] !== ConstCode::IS_YES) {
            $joinSub = NodeModel::getUserNodeIDArray($this->params['UserID']);
            $query->whereIn('NodeID', $joinSub);
        }

        return $query->get()->keyBy('menuId')->toArray();
    }

    /**
     * @Desc   获取用户的后台菜单树
     * @return array
     * @throws \App\Exceptions\ThrowException
     * @author yashuai<1762910894@qq.com>
     */
    public function getUserAdminNodeTree()
    {
        $node = $this->getUserNode();
        foreach ($node as &$val) {
            $val['hide'] = $val['NodeShowType'] == ConstCode::IS_NO;
            if ($val['parentId'] != 0) {
                $val['path'] = $val['component'] = "/" . $val['ControllerName'] . "/" . $val['ActionName'];
                unset($val['ControllerName'], $val['ActionName']);
            }
            unset($val['NodeShowType']);
        }
        $node = UtilArray::listToTree($node, 'menuId', 'parentId', 'children');

        foreach ($node as &$val) {

            if ($val['parentId'] == 0) {
                if (isset($val['children'])) {
                    $val['component'] = '';
                    $val['path']      = "/" . $val['ControllerName'];
                } else {
                    $val['path'] = $val['component'] = "/" . $val['ControllerName'] . "/" . $val['ActionName'];
                }
                unset($val['ControllerName'], $val['ActionName'], $val['NodeShowType']);
            }
        }

        return $node;
    }

    /**
     * @Desc 数据转为表结构数据
     * @return array
     * @throws \App\Exceptions\ThrowException
     * @author yashuai<1762910894@qq.com>
     */
    private function getParamsTableData()
    {
        $parentID = _array_field($this->params, 'ParentID', 0);
        if (!empty($parentID) && empty(NodeModel::getInfo($parentID, 'NodeID'))) {
            _throw('上级菜单不存在', 106002);
        }

        $data = [
            'ParentID'       => $parentID,
            'NodeName'       => $this->params['NodeName'],
            'ControllerName' => $this->params['ControllerName'],
            'ActionName'     => $this->params['ActionName'],
            'EventType'      => $this->params['ControllerName'] . '.' . $this->params['ActionName'],
            'NodeType'       => $this->params['NodeType'],
            'NodeShowType'   => $this->params['NodeShowType'],
            'NodeOrder'      => $this->params['NodeOrder'],
            'NodeStatus'     => ConstCode::BASIC_STATUS_NORMAL,
        ];
        if (isset($this->params['NodeIcon'])) {
            $data['NodeIcon'] = $this->params['NodeIcon'];
        }
        return $data;
    }

}
